package com.zHan.system.controller.system;


import com.zHan.common.result.Result;
import com.zHan.model.dto.AssginDeptDto;
import com.zHan.model.system.SysDept;
import com.zHan.model.system.SysUser;
import com.zHan.system.anno.Log;
import com.zHan.system.exception.MyException;
import com.zHan.system.menu.BusinessType;
import com.zHan.system.service.ISysDeptService;
import com.zHan.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.regex.Pattern;

/**
 * <p>
 * 组织机构 前端控制器
 * </p>
 *
 * @author zHan
 * @since 2023-06-24
 */
@RestController
@Slf4j
@Api(tags = "部门管理接口")
@RequestMapping("/admin/system/sysDept")
public class SysDeptController {

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 新增部门
     *
     * @param sysDept
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('bnt.sysDept.add')")
    @ApiOperation(value = "新增部门")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    public Result save(@RequestBody SysDept sysDept) {
        String phonePattern = "^1[3|4|5|7|8][0-9]{9}$";
        // 手机号判断
        if (!Pattern.matches(phonePattern, sysDept.getPhone())) {
            throw new MyException(201, "请输入正确的手机号");
        }
        boolean isSuccess = sysDeptService.saveDept(sysDept);
        if (isSuccess) {
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 删除部门
     *
     * @param id
     * @return
     */
    @DeleteMapping("/remove/{id}")
    @PreAuthorize("hasAuthority('bnt.sysDept.remove')")
    @ApiOperation(value = "删除部门")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    public Result remove(@PathVariable Long id) {
        boolean isSuccess = sysDeptService.removeDeptById(id);
        if (isSuccess) {
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 批量删除部门
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/batchRemove")
    @PreAuthorize("hasAuthority('bnt.sysDept.remove')")
    @ApiOperation(value = "批量删除部门")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    public Result batchRemove(@RequestBody List<Long> ids) {
        boolean isSuccess = sysDeptService.batchRemoveDept(ids);
        if (isSuccess) {
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 修改部门
     *
     * @param sysDept
     * @return
     */
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('bnt.sysDept.update')")
    @ApiOperation(value = "修改部门")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    public Result update(@RequestBody SysDept sysDept) {
        boolean isSuccess = sysDeptService.updateById(sysDept);
        if (isSuccess) {
            return Result.ok();
        }
        return Result.fail();
    }

    /**
     * 部门列表（树形）
     *
     * @return
     */
    @GetMapping("/findNodes")
    @ApiOperation(value = "部门列表")
    public Result findNodes() {
        List<SysDept> sysDeptList = sysDeptService.selectNodes();
        if (!sysDeptList.isEmpty()) {
            return Result.ok(sysDeptList);
        }
        return Result.fail();
    }

    /**
     * 根据id查询单个部门
     *
     * @param id
     * @return
     */
    @GetMapping("/findNode/{id}")
    @ApiOperation(value = "查询单个部门")
    public Result findNode(@PathVariable String id) {
        SysDept dept = sysDeptService.getById(id);
        if (dept != null) {
            return Result.ok(dept);
        }
        return Result.fail();
    }

    /**
     * 根据id查询单个部门及其父节点集合
     *
     * @param id
     * @return
     */
    @GetMapping("/findNodes/{id}")
    @ApiOperation(value = "根据id查询单个部门及其父节点集合")
    public Result findNodes(@PathVariable String id) {
        List<SysDept> sysDeptList = sysDeptService.selectNodesById(id);
        if (!sysDeptList.isEmpty()) {
            return Result.ok(sysDeptList);
        }
        return Result.ok('空');
    }

    /**
     * 获取用户的部门数据
     *
     * @param userId
     * @return
     */
    @GetMapping("/toAssign/{userId}")
    @ApiOperation(value = "获取用户的角色数据")
    public Result toAssign(@PathVariable String userId) {
        List<SysDept> sysDeptList = sysDeptService.selectDeptsByUserId(userId);
        if (!sysDeptList.isEmpty()) {
            return Result.ok(sysDeptList);
        }
        return Result.fail();
    }

    /**
     * 给用户分配部门
     *
     * @param assginDeptDto
     * @return
     */
    @PostMapping("/doAssign")
    @PreAuthorize("hasAuthority('bnt.sysUser.assignDept')")
    @ApiOperation(value = "给用户分配部门")
    @Log(title = "部门管理", businessType = BusinessType.OTHER)
    public Result doAssign(@RequestBody AssginDeptDto assginDeptDto) {
        boolean isSuccess = sysDeptService.assignDeptToUser(assginDeptDto);
        SysUser sysUser = sysUserService.getById(assginDeptDto.getUserId());
        if (isSuccess) {
            return Result.ok(sysUser);
        }
        return Result.fail();
    }

    /**
     * 更改部门状态
     *
     * @param id
     * @param status
     * @return
     */
    @PutMapping("/updateStatus/{id}/{status}")
    @PreAuthorize("hasAuthority('bnt.sysDept.update')")
    @ApiOperation(value = "更改部门状态")
    @Log(title = "部门管理", businessType = BusinessType.STATUS)
    public Result updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        boolean isSuccess = sysDeptService.updateStatus(id, status);
        if (isSuccess) {
            return Result.ok();
        }
        return Result.fail();
    }

}

